package com.jenkins.test.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: {@link JacksonUtil}
 * @Description: 皆可送JSON工具
 * @author: Lanzhou
 * @date: 2020/12/6 23:10
 * @QQ: 1627518680
 * @Copyright:2020 All rights reserved.
 */
@Slf4j
public class JacksonUtil<T> {

    /**
     * 搞个静态对象
     */
    private static ObjectMapper mapper = new ObjectMapper();


    /**
     * 对象转JSON
     *
     * @param t
     * @return
     */
    public static <T> String objToJson(T t) {
        try {
            return mapper.writeValueAsString(t);
        } catch (JsonProcessingException e) {
            log.error("对象转JSON失败", e);
        }
        return null;
    }


    /**
     * JSON转对象
     *
     * @param json
     * @return
     */
    public static <T> T jsonToObj(String json, Class<T> type) {
        try {
            return mapper.readValue(json, type);
        } catch (JsonProcessingException e) {
            log.error("对象转JSON失败", e);
        }
        return null;
    }


}
